package com.hxzy.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.hxzy.common.util.MarketingThreadLocalUtil;
import com.hxzy.controller.mobile.login.resp.MobileLoginResp;
import com.hxzy.controller.vue.login.resp.AdminLoginResp;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Author wy
 * @Description mybatis-plus字段自动填充功能(spring ioc面向切面编程)
 * @Date 2023/9/1 11:23
 * @Version 1.0
 */
@Component
public class MybatisplusMetaObjectHandler implements MetaObjectHandler {

    /**
     * 只能在调用mybatis-plus中的 save方法才有生效
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        // createBy
        String createBy="";
        //是否是后台用户(商家或管理员)
        AdminLoginResp adminLoginResp = MarketingThreadLocalUtil.adminThreadLocal.get();
        if(adminLoginResp!=null){
            createBy= adminLoginResp.getName();
        }

        //是否是前端用户
        MobileLoginResp mobileLoginResp = MarketingThreadLocalUtil.mobileThreadLocal.get();
        if(mobileLoginResp!=null){
            createBy= mobileLoginResp.getUserName();
        }

        this.strictInsertFill(metaObject, "createBy", String.class, createBy);
    }

    /**
     * 只允许在调用mybatis-plus中的 update开头的方法才生效
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
        // createBy
        String updateBy="";
        //是否是后台用户(商家或管理员)
        AdminLoginResp adminLoginResp = MarketingThreadLocalUtil.adminThreadLocal.get();
        if(adminLoginResp!=null){
            updateBy= adminLoginResp.getName();
        }

        //是否是前端用户
        MobileLoginResp mobileLoginResp = MarketingThreadLocalUtil.mobileThreadLocal.get();
        if(mobileLoginResp!=null){
            updateBy= mobileLoginResp.getUserName();
        }

        this.strictUpdateFill(metaObject, "updateBy", String.class, updateBy);
    }
}
